package vc.learn.springcloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.*;
import org.springframework.security.core.context.*;
import org.springframework.security.core.userdetails.*;
import org.springframework.web.bind.annotation.*;
import vc.learn.springcloud.entity.User;
import vc.learn.springcloud.repository.UserRepository;

import java.util.*;

/**
 * Created on 2018-06-30 下午7:49.
 *
 * @author <a href="mailto:vague.fu@outlook.com">vague.fu</a>
 * @version 0.0.1
 * @since 0.0.1
 */
@Slf4j
@RestController
public class UserController {
    private UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping("/{id}")
    public User findById(@PathVariable Long id){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(principal instanceof UserDetails){
            UserDetails userDetails = (UserDetails) principal;
            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
            for(GrantedAuthority authority : authorities){
                log.info("当前用户:{}, 角色:{}.",((UserDetails) principal).getUsername(),authority.getAuthority());
            }
        }else{
            log.error("Security principal is conrrect.");
        }
        return this.userRepository.findOne(id);
    }
}
